<template>
	<view class="container">
		<view class="top">
			<view class="title">我的相册</view>
			<view>当前已有{{ num }}张图片，还可以免费上传{{ free - num }}张</view>
		</view>
		<view class="list">
			<view class="imgs" v-for="item in list">
				<img class="img" :src="item.src" alt="" mode="aspectFit">
				<button class="del" @click="del(item)">删除</button>
			</view>
		</view>
		<view class="empty" v-if="list.length == 0">
			<text>请先在下方选择上传图片</text>
		</view>
		<div class="footer">
			<button @tap="back" class="back">返回</button>
			<button @tap="make" class="make">生成贺卡</button>
			<button @tap="submit" class="upload">上传图片</button>
		</div>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				options: {},
				openId: '',
				envId: '',
				filesArr: [],
				list: [
					// {
					// 	src: 'https://mmbiz.qpic.cn/mmbiz_jpg/Qs5ZVics1SyDclDw0M0ibJXGbZmq6VaLaiahf36HJJqqZ4bFDwBwyvVMroRwDqf6QkLjePicmMMeo4EticicJDruoia2g/640?wx_fmt=jpeg&amp;from=appmsg',
					// 	index: 0
					// },
					// {
					// 	src: 'https://mmbiz.qpic.cn/mmbiz_jpg/Qs5ZVics1SyDclDw0M0ibJXGbZmq6VaLaiawAjKic3IeocEA3LfnJib51r2mib8icEr8HV2pdcctOyicNB6ticQJichFqFCg/640?wx_fmt=jpeg&amp;from=appmsg',
					// 	index: 1
					// },
					// {
					// 	src: 'https://mmbiz.qpic.cn/mmbiz_jpg/Qs5ZVics1SyDclDw0M0ibJXGbZmq6VaLaia7qrqCXxCeeTCHSFkhusba12Ry8iayPIzYaoOib3SmPdQROiacDb5Gp7mg/640?wx_fmt=jpeg&amp;from=appmsg',
					// 	index: 2
					// }
				],
				num: 0,
				free: 5
			}
		},

		onLoad(options) {
			const that = this;
			this.options = options;
			wx.showLoading({
				title: '',
			});
			wx.login({
				// 调用接口获取登录凭证（code）
				success: (Result) => {
					// 向后台发起request.login请求,用code换取用户登录态信息openid,存储为token;
					this.$apis.getopenid({
						code: Result.code,
						appid: this.$apis.appId,
					}).then((token) => {
						wx.hideLoading();
						// 存储用户登录态信息token
						wx.setStorageSync('token', token);
						that.openId = token.openid
					}).catch(error => {
						console.log("换取登录态token失败：", error)
					});
				},
				fail: (res) => {
					console.log("获取登录凭证code失败！", res)
				}
			})
		},
		methods: {
			del(row) {
				this.list = this.list.filter(item => item.index !== row.index);
				this.num = this.list.length;
			},
			back() {
				uni.navigateBack({
					delta: 1
				});
			},
			make() {
				const that = this;
				if (parseInt(this.num) === 0) {
					uni.showToast({
						icon: 'error',
						title: '至少上传1张图片'
					})
					return false
				}
				console.log('this.options', this.options);
				const ablums = this.list.map(item => item.src).join(',');
				let data = {
					"ablums": ablums,
					'title': this.options.title,
					'templateid': this.options.templateid, //相册自定义的模版ID
					'appid': this.$apis.appId,
					'openid': this.openId
				};
				console.log('data', data);
				this.$apis.setalbum(data).then(result => {
					uni.showModal({
						title: '提示',
						content: '生成完毕,看看效果',
						success: function(res) {
							if (res.confirm) {
								console.log('用户点击确定');
								uni.navigateTo({
									url: '/pages/album/'+that.options.type+'?' + 'templateid=' + result
										.templateid + '&showano=' + result.showano + '&ano=' +
										result.ano + '&title=' +
										result.title
								});
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});

				})
			},
			submit() {
				const that = this;
				if (parseInt(this.num) > 4) {
					uni.showToast({
						title: "最多上传5张",
						icon: 'error'
					});
					return false
				}
				uni.chooseImage({
					count: 1,
					fail(err) {
						uni.showToast({
							title: '图片选择失败，请重试'
						})
					},
					success: (chooseImageRes) => {
						const tempFilePaths = chooseImageRes.tempFilePaths[0];

						// 容量校验
						let resSize = chooseImageRes.tempFiles[0].size;
						if (resSize > 6291456) {
							uni.showToast({
								title: "图片不能超过6MB",
								icon: 'error'
							});
							return
						}

						// 类型校验
						const fileType = tempFilePaths.split('.').pop().toLowerCase();
						if (fileType !== 'png' && fileType !== 'jpg' && fileType !== 'jpeg') {
							uni.showToast({
								title: "只能上传png、jpg、jpeg格式",
								icon: 'error'
							});
							return
						}


						// 图片转换成base64
						const fileManager = wx.getFileSystemManager();
						const base64 = fileManager.readFileSync(tempFilePaths, 'base64');

						// wx.showToast({
						// 	icon: 'none',
						// 	title: '图片正常', //图片含有违法信息，请换张说明图
						// })

						uni.showLoading({
							title: "图片校验中",
						});


						uni.showLoading({
							title: "上传中",
						});
						uni.uploadFile({
							url: 'https://wx.12359.xyz/api/v1/FileUploadApi', //上传地址
							filePath: tempFilePaths,
							name: 'iFile',
							formData: {
								'user': 'test'
							},
							success: (uploadFileRes) => {
								let res = JSON.parse(uploadFileRes.data)
								uni.hideLoading();
								if (parseInt(res.code) === 0) {
									uni.showToast({
										title: res.msg
									});
									let path = res.data.file_path;
									this.num++;
									that.list.push({
										"index": this.num + 1,
										"src": path
									})
								} else {
									console.log('res===>', res);
									uni.showToast({
										icon: 'error',
										title: res.original.data.data
									});
								}
							},
							fail(err) {
								uni.hideLoading();
								uni.showToast({
									icon: 'error',
									title: err
								});
								console.log(err);
							}
						});
					}
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import "make.scss";
</style>